<?php
// 会员优惠券
namespace app\shop\controller;

use think\Db;
use think\Request;
use think\Session;
use think\Controller;
use app\shop\model\GoodsType as GoodsTypeModel;
use app\shop\model\MemberCoupon as MemberCouponModel;

class MemberCoupon extends Controller
{
    /**
     * 优惠券主页
     */
    public function index()
    {
        // 获取会员ID
        $memberId = Session::get('member_id');

        // 获取参数
        $inquire = Request::instance()->param('select', 'not_used');
        $condition['member_id'] = ['eq', $memberId];

        switch ($inquire) {
            // 已使用
            case 'used':
                $condition['status'] = ['eq', 1];
                break;
            // 已过期
            case 'expired':
                $condition['status'] = ['eq', 2];
                $condition['end_time'] = ['elt', time()];
                break;
            // 未使用
            case 'not_used':
                $condition['status'] = ['eq', 2];
                $condition['end_time'] = ['egt', time()];
                break;
        }


        $memberCoupon = new MemberCouponModel();

        // 已使用
        $rank['used'] = $memberCoupon->where(['member_id' => $memberId, 'status' => 1])->count();
        // 未使用
        $rank['not_used'] = $memberCoupon->where(['member_id' => $memberId, 'status' => 2, 'end_time' => ['gt', time()]])->count();
        // 已过期
        $rank['expired'] = $memberCoupon->where(['member_id' => $memberId, 'status' => 2, 'end_time' => ['elt', time()]])->where(['end_time' => ['neq', 0]])->count();

        // 获取数据
        $result = $memberCoupon->where($condition)->field('member_id,create_time,status', true)->order(['id' => 'desc'])->paginate(16, false, ['query' => $inquire]);

        foreach ($result as &$value) {
            // 平台优惠券
            if ($value['shop_id']==0) {
                $type_id = Db::name('coupon')->where('id',$value['coupon_id'])->value('parenTid');
                $value['type_name'] = Db::name('goods_type')->where('id',$type_id)->value('title');

            }else{
                $value['type_name'] = Db::name('shop')->where('member_id',$value['shop_id'])->value('title');
            }
        }


        return $this->fetch('', [
            'mate_head' => '我的优惠券',
            'data'      => $result,
            'rank'      => $rank,
        ]);
    }
}